<?php

namespace app\admin\controller\order;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\ChannelCarrier;
use app\common\model\Countries;
use app\common\model\Orders;
use app\common\service\import\Order;
use app\common\service\orders\OrderService;
use app\common\status\BaseStatus;
use Env;
use RuntimeException;

class ManagerController extends BaseController
{
    /**
     * 显示订单列表
     * @return mixed
     */
    public function index()
    {
        $this->assign('platform', AccountPlatform::getAll());
        $this->assign('send_date', [-1 => '昨天', 0 => '今天', -6 => '7天前', -59 => '60天前']);
        $this->assign('sort', ['order_source_create_time' => '订单创建时间', 'total_price' => '订单价格', 'latest_delivery_time' => '剩余发货时间']);
        $this->assign('carrier', ChannelCarrier::getAll());
        $this->assign('select_order', [
            'order_no' => '平台订单号',
            'order_sn' => '内部统一单号',
            'shipping_code' => '运单号',
            'detail_sku' => '内部SKU',
            'detail_platform_sku' => '平台SKU',
            'buyer_email' => '买家邮箱',
            'buyer_phone' => '买家电话',
            'buyer_mobile' => '买家手机',
        ]);
        $this->assign("print_status", Orders::$PRINT_STATUS);
        $this->assign("label_status", [0 => '未生成', 1 => '已生成']);
        $this->assign('account', Account::getAll());
        $this->assign('order_status', Orders::$ORDER_STATUS);
        $this->assign('send_status', Orders::$SEND_STATUS);
        $country = Countries::field(["code_two","name_ch"])->order("name_en")->select();
        $this->assign('select_country', $country);
        $logistics = ChannelCarrier::field(['carrier_name', 'carrier_num', 'carrier_id'])
            ->where(['status' => ChannelCarrier::STATUS_Y])
            ->order("carrier_name")->select();
        $this->assign('select_logistics', $logistics);
        if($this->request->isAjax())
        {
            $orders = OrderService::getInstance()->search($this->request->request());
            return apiResponsePage($orders);
        }
        return $this->fetch('index');
    }

    public function question()
    {
        $this->assign("other_filter", ['order_status' => ORders::ORDER_EXCEPTION]);
        return $this->index();
    }

    /**
     * 删除订单
     * @return array
     * @date 2020/09/02
     * @author longli
     */
    public function delete()
    {
        $ids = $this->request->get("ids");
        return OrderService::getInstance()->deleteOrderById($ids)
                ? apiResponse(BaseStatus::CODE_NORMAL, [], '删除成功')
                : apiResponse(BaseStatus::CODE_FAULT, [], '删除失败');
    }

    /**
     * 更新订单
     * @return array
     * @date 2020/09/02
     * @author longli
     */
    public function edit()
    {
        $orderId = $this->request->request("order_id");
        if(empty($orderId)) return apiResponse(BaseStatus::CODE_FAULT, [], '非法请求');
        $field = $this->request->post("field");
        $value = $this->request->post("value");
        if((is_array($field) && !is_array($value)) || (empty($field) || (empty($value) && !is_numeric($value))))  return apiResponse(BaseStatus::CODE_FAULT, [], '非法参数');
        if(is_array($field))
        {
            $data = [];
            foreach($field as $k => $f)
            {
                $data[$f] = $value[$k];
            }
        }
        else
        {
            $data = [$field => $value];
        }
        return Orders::editByOrderId($orderId, $data)
            ? apiResponse(BaseStatus::CODE_NORMAL, [], '更新成功')
            : apiResponse(BaseStatus::CODE_FAULT, [], '更新失败');
    }

    public function look()
    {
        if($this->request->isPost())
        {
            if(!Tools::isJson($this->request->getContent(), $data)) return apiResponse(BaseStatus::CODE_FAULT, [], '非法请求');
            return OrderService::getInstance()->addOrder($data)
                ? apiResponse(BaseStatus::CODE_NORMAL, [], '订单保存成功')
                : apiResponse(BaseStatus::CODE_FAULT, [], '订单保存失败');
        }
        else
        {
            $orderId = $this->request->request("order_id");
            $order = Orders::with(['track', 'detail' => function($query){$query->hidden(['ext_json']);}])->get($orderId);
            $this->assign("order", $order);
            $this->assign("country", Countries::order("name_ch")->field(["name_ch", "code_two"])->select());
            $temp = array_flip(Orders::$ORDER_STATUS)[$order->order_status];
            $process = $temp == 0 ? 0 : round($temp / Orders::ORDER_SUCCESS * 100);
            $this->assign("process" , $process);
            return $this->fetch();
        }
    }

    /**
     * 导入订单
     * @return array
     * @date 2020/09/03
     * @author longli
     */
    public function import()
    {
        $file = $this->request->request("path");
        if(Tools::startWith($file, '/')) $file = Env::get("root_path") . "public{$file}";
        $orderImport = new Order($file);
        try
        {
            $orderImport->run();
            return apiResponse(BaseStatus::CODE_NORMAL, [], '导入成功');
        }catch(RuntimeException $e)
        {
            return apiResponse(BaseStatus::CODE_FAULT, [], $e->getMessage());
        }
    }

    /**
     * 导出文件
     * @return array
     * @date 2020/09/03
     * @author longli
     */
    public function export()
    {
        $ids = $this->request->request("ids");
        $startDate = $this->request->request("start_date");
        if(empty($ids) && empty($startDate)) return apiResponse(BaseStatus::CODE_FAULT, [], "非法导出，请检查导出条件");
        $condition = [];
        if(!empty($ids)) $condition[] = ['order_id', 'in', $ids];
        if(!empty($startDate)) $condition = array_merge($condition, OrderService::getInstance()->parseLayuiRangeDate('order_source_create_time', $startDate));
        $orderExport = new \app\common\service\export\Order();
        $file = $orderExport->runExcel($condition);
        return apiResponse(BaseStatus::CODE_NORMAL, ["src" => urlencode($file)], "导出成功");
    }
}
